package com.xy.demo.service.impl;


import com.xy.demo.Util.ResultUtil;
import com.xy.demo.Util.Util;
import com.xy.demo.model.Params;
import com.xy.demo.model.ResultInfo;
import com.xy.demo.service.FcService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class FcServiceImpl implements FcService {
    @Override
    public ResultInfo randomOne(Params params) {
        Map<Integer,List<String>> map = new HashMap<>();
        for(int i = 0 ; i < params.getBound(); i++){
            List<String> list = new ArrayList<>();
            list = getKlbNum(params.getNum(),params.getMin(),params.getMax(),list);
            if(list.size()>0){
                String str = list.stream().map(String::toString).collect(Collectors.joining(","));
                if(!Util.isEmpty(map.get(list.size()))){
                    List<String> arr = map.get(list.size());
                    arr.add(str);
                    map.put(list.size(),arr);
                }else{
                    List<String> arr = new ArrayList<>();
                    arr.add(str);
                    map.put(list.size(),arr);
                }
            }
        }
        ResultInfo resultInfo = ResultUtil.getResultInfoOk(map);
        return resultInfo;
    }

    public static List<String> getKlbNum(int num, int min, int max, List<String> list){
        Random random = new Random();
        if(Util.equals(list.size(),num)){
            return list;
        }else if(min>=max){
            list = new ArrayList<>();
            getKlbNum(num,1,max,list);
        }else if(Util.equals(min,Util.subtract(max,1))){
            int r = min+random.nextInt(2);
            list.add(Util.toString(r));
            getKlbNum(num,max,max,list);
        }else{
            int r = min+random.nextInt(max+1-min);
            list.add(Util.toString(r));
            getKlbNum(num,r+1,max,list);
        }
        return list;
    }
}
